<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
    <title>big</title>
    <style>
        body{
            padding: 50px;
            display: flex;
        }
        .container{
            width:300px;
            height:300px;
            position: relative;
            display: inline-block;
        }
        .container img{
            width:100%;
            height:100%;
        }
        .magnifier{
            width:100px;
            height:100px;
            background: rgba(100,0,0,0.2);
            position: absolute;
            left:0;
            top:0;
            display: none;
        }
        .preview{
            width:300px;
            height:300px;
            position: relative;
            display: inline-block;
            overflow:hidden;
        }
        .preview img{
            position: absolute;
            width:900px;
            height:900px;
            left:0;
            top:0;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <img src="images/small.jpg"/>
        <div class="magnifier"></div>
    </div>
    <div class="preview">
        <img src="images/big.jpg"/>
    </div>
    <script>
        //获取左侧的小图的容器
        let container = document.querySelector('.container');
        //获取左侧的遮罩层
        let magnifier = document.querySelector('.magnifier');
        //获取右侧的放大预览区域
        let preview = document.querySelector('.preview');
        //获取右侧的放大后的图片
        let bigImg = document.querySelector('.preview img');
        //给容器添加鼠标移动事件
        container.addEventListener('mousemove',(event)=>{
            //先获取容器的矩形信息
            let containerRect = container.getBoundingClientRect();
            //计算放大镜的left值，等于当前鼠标点击位置距离视口左边缘的距离-矩形的left-放大镜宽度的一部
            let x = event.clientX - containerRect.left - magnifier.offsetWidth/2;
            let y = event.clientY - containerRect.top - magnifier.offsetHeight/2;
            //容器的宽度-放大镜的宽度就是放大镜的最大left值
            x = Math.max(0,Math.min(x,container.clientWidth-magnifier.offsetWidth));
            //容器的高度-放大镜的高度就是放大镜的最大top值
            y = Math.max(0,Math.min(y,container.clientHeight-magnifier.offsetHeight))
            magnifier.style.left = x+'px';
            magnifier.style.top = y+'px';
            magnifier.style.display = 'block';
            bigImg.style.left = -x*3+'px';
            bigImg.style.top = -y*3+'px';
            bigImg.style.display = 'block';
        });
        container.addEventListener('mouseleave',()=>{
            magnifier.style.display = 'none';
            bigImg.style.display = 'none';
        });
    </script>
</body>
</html>